package com.antsoft.database.druid;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.antsoft.database.mybatis.DbType;
import com.antsoft.database.mybatis.ReadWriteSplitRoutingDataSource;

/**
 * Created by Jason on 2017/3/6.
 */
@Configuration
//@AutoConfigureAfter({DataSourceConfiguration.class})
@ConditionalOnClass({EnableTransactionManagement.class})  
@Import({ DataSourceConfiguration.class})  
@MapperScan(basePackages = {"com.antsoft.mapper"}, sqlSessionFactoryRef = "sqlSessionFactory")
public class MybatisConfiguration
//       extends MybatisAutoConfiguration
{

    private static Log logger = LogFactory.getLog(MybatisConfiguration.class);
    
    @Resource(name = "masterDataSource")
    private DataSource masterDataSource;
    
    @Resource(name = "slaveDataSource")
    private DataSource slaveDataSource;

    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        logger.info("-------------------- 重载父类 sqlSessionFactory init ---------------------");
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(roundRobinDataSouceProxy());
//        return super.sqlSessionFactory(roundRobinDataSouceProxy());
        return sqlSessionFactoryBean.getObject();
    }


//    @Bean
//    public SqlSessionFactory sqlSessionFactory2() throws Exception {
//        logger.info("-------------------- 重载父类 sqlSessionFactory init ---------------------");
//        return super.sqlSessionFactory(slaveDataSource);
//    }
    
//    @Override
//    public void setEnvironment(Environment environment) {
//        this.propertyResolver = new RelaxedPropertyResolver(environment,"mybatis.");
//    }
//
//    @Bean
//    @ConditionalOnMissingBean
//    public SqlSessionFactory sqlSessionFactory(){
//        try{
//            SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
//            sessionFactoryBean.setDataSource(roundRobinDataSouceProxy());
//            sessionFactoryBean.setTypeAliasesPackage(propertyResolver.getProperty("typeAliasesPackage"));
//            sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(
//                    propertyResolver.getProperty("mapperLocations")
//            ));
//            sessionFactoryBean.setConfigLocation(new DefaultResourceLoader().getResource(
//                    propertyResolver.getProperty("configLocation")
//            ));
//            return sessionFactoryBean.getObject();
//        }catch (Exception e){
//            logger.warn("Could not confiure mybatis session factory");
//            return null;
//        }
//    }

    @Bean
    public AbstractRoutingDataSource roundRobinDataSouceProxy(){
    	logger.info("--------------------组装数据源 ---------------------");
        ReadWriteSplitRoutingDataSource proxy = new ReadWriteSplitRoutingDataSource();
//      Map<Object,Object> targetDataResources = new ClassLoaderRepository.SoftHashMap();
        Map<Object,Object> targetDataResources = new HashMap<Object,Object>();
        targetDataResources.put(DbType.MASTER,masterDataSource);
        targetDataResources.put(DbType.SLAVE,slaveDataSource);
        proxy.setDefaultTargetDataSource(masterDataSource);
        proxy.setTargetDataSources(targetDataResources);
        return proxy;
    }
}
